package com.hefan.oms.listener;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.cat.common.constant.RedisKeyConstant;
import com.cat.common.meta.ImCustomMsgEnum;
import com.cat.tiger.service.JedisService;
import com.cat.tiger.util.CollectionUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hefan.common.ons.TopicRegistry;
import com.hefan.common.ons.TopicRegistryDev;
import com.hefan.common.ons.TopicRegistryTest;
import com.hefan.common.ons.listener.GLLMessageListener;
import com.hefan.live.itf.LiveLogPersonService;
import com.hefan.oms.bean.OrderRedPacketDetail;
import com.hefan.oms.bean.RedPacketVo;
import com.hefan.oms.dao.ExpendDao;
import com.hefan.oms.dao.OrderRedPacketDao;
import com.hefan.oms.dao.OrderRedPacketDetailDao;
import com.hefan.oms.dao.PresentDao;
import com.hefan.oms.itf.MessageService;
import com.hefan.oms.itf.RedPacketService;
import com.hefan.user.bean.WebUser;
import com.hefan.user.itf.WebUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.profiler.Profiler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * Created by hbchen on 2016/10/12.
 * 发送红包逻辑：从直播间随机获取当前用户中奖，存入redis中
 */
@Component
public class RedPacketListener implements GLLMessageListener {

    @Resource
    OrderRedPacketDao orderRedPacketDao;
    @Resource
    OrderRedPacketDetailDao orderRedPacketDetailDao;
    @Resource
    ExpendDao expendDao;
    @Resource
    PresentDao presentDao;
    @Resource
    JedisService jedisService;
    @Resource
    LiveLogPersonService liveLogPersonService;
    @Resource
    WebUserService webUserService;
    @Resource
    RedPacketService redPacketService;
    @Resource
    private MessageService privateMessageService;

    private Logger logger = LoggerFactory.getLogger(RedPacketListener.class);

    @Override
    public TopicRegistry getTopicRegistry() {
        return TopicRegistry.HEFANTV_RED;
    }

    @Override
    public TopicRegistryDev getTopicRegistryDev() {
        return TopicRegistryDev.HEFANTV_RED_DEV;
    }

    @Override
    public TopicRegistryTest getTopicRegistryTest() {
        return TopicRegistryTest.HEFANTV_RED_TEST;
    }


    /**
     * 虚拟用户不能发送红包
     * @param message
     * @param consumeContext
     * @return
     */
    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {

        Profiler profiler = new Profiler("RedPacketListener");
        profiler.start("start");

        String realTopic = message.getTag();
        logger.info("RedPacketListener topic: {}, realTopic : {}, msg_body: {}", message.getTopic(), realTopic, new String(message.getBody()));
        try {
            Map map = new ObjectMapper().readValue(message.getBody(), Map.class);
            if (CollectionUtils.isEmpty(map) || !map.containsKey("redPacketVo")) {
                logger.error("RedPacketListner参数{}错误",map);
                return Action.CommitMessage;
            }
            String redPacketStr = (String)map.get("redPacketVo");
            logger.info("红包队列接受参数"+redPacketStr);

            RedPacketVo redPacketVo = JSON.parseObject(redPacketStr, RedPacketVo.class);
            WebUser webUser = webUserService.getWebUserInfoByUserId(redPacketVo.getUserId());
            if (webUser==null){
                logger.error("webUser为null！！！");
                return Action.CommitMessage;
            }
            profiler.start("start0----");
            long orderId = redPacketService.pushRedPacket(redPacketVo,webUser);
            logger.error("start0--------------");
            //由于批量插入无法返回id，只好再把明细查一下
            List<OrderRedPacketDetail> ids = orderRedPacketDetailDao.selectRedPackDetailIds(orderId);
            logger.error("start1--------------",ids.size());
            //从直播间取n个人过滤当前用户，告诉客户端，相关信息存redis
            //确定可中红包的范围
            profiler.start("start1----");
            int number=redPacketVo.getPersonNum();
            List<Map<String,String>> plist = Lists.newArrayList();
            //红包数==1,中奖人为主播
            if (number == 1) {
                Map<String,String> temp= Maps.newHashMap();
                temp.put("userId",redPacketVo.getZhuboId());
                plist.add(temp);
            }else{
                //plist = liveLogPersonService.queryUserIDsForLiveRoomRedPacket(redPacketVo.getLiveUuid(),number-1,redPacketVo.getUserId());
                //从redis取观看直播人数
                plist = liveLogPersonService.getIdsFromRedisForLive(redPacketVo.getZhuboId(),number-1,redPacketVo.getUserId());
                logger.info("红包中奖人{}",plist.toString());
                Map<String,String> temp= Maps.newHashMap();
                temp.put("userId",redPacketVo.getZhuboId());
                plist.add(temp);
            }
            logger.error("start1--------------{}",plist.size());
            // 不能获取直播人数时
            String[] strings = new String[ids.size()];
            for (int i = 0; i < ids.size(); i++) {
                strings[i] = JSON.toJSONString(ids.get(i));
            }
            profiler.start("start2----");
            //红包多久过期，和产品确认
            String mkey = String.format(RedisKeyConstant.RED_PACKET_MONEY_KEY,orderId);
            String pkey = String.format(RedisKeyConstant.RED_PACKET_PEOPLE_KEY, orderId);
            try {
                logger.error("start2111--------------");
                if (!CollectionUtils.isEmpty(plist)) {
                    jedisService.sadd(mkey, strings);
                    jedisService.setStr(pkey, JSON.toJSONString(plist));
                    logger.error("start211122--------------");
                }
            } catch (Exception e) {
                logger.error("缓存红包redis异常{}",e.getMessage());
                return Action.ReconsumeLater;
            }
            profiler.start("start3----");
            //红包礼物
            privateMessageService.dealRedPacketImMessage(redPacketVo,ImCustomMsgEnum.LivePresent.getType(),ImCustomMsgEnum.LivePresent.getMsg(),webUser,plist,orderId);
            //主播盒饭数变化
            privateMessageService.dealRedPacketImMessage(redPacketVo,ImCustomMsgEnum.PresentChange.getType(),ImCustomMsgEnum.PresentChange.getMsg(),webUser,null,0);
        } catch (Exception e) {
            logger.error("处理红包逻辑异常",e);
            return Action.ReconsumeLater;
        }
        return Action.CommitMessage;
    }

}
